/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package madmac.hibernate.util;

import java.io.Serializable;
import madmac.exception.DataAccessLayerException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import madmac.hibernate.util.HibernateUtil;

/**
 *
 * @author madmac
 */
public abstract class AbstractDao {

	private Session session;
	private Transaction tx;

	public AbstractDao() throws DataAccessLayerException {
		HibernateUtil.getInstance().buildIfNeeded();
      startOperation();
	}

   protected Serializable save(Object obj) throws DataAccessLayerException {
      Serializable serial = null;
      try {
         tx = session.beginTransaction();
         serial = session.save(obj);
         tx.commit();
      } catch (HibernateException e) {
         handleException(e);
      }
      return serial;
   }

	protected void saveOrUpdate(Object obj) throws DataAccessLayerException {
		try {
         tx = session.beginTransaction();
			session.saveOrUpdate(obj);
			tx.commit();
		} catch (HibernateException e) {
			handleException(e);
		}
	}

	protected void delete(Object obj) throws DataAccessLayerException {
		try {
         tx = session.beginTransaction();
			session.delete(obj);
			tx.commit();
		} catch (HibernateException e) {
			handleException(e);
		}
	}

	protected Object find(Class clazz, Long id) throws DataAccessLayerException {
		Object obj = null;
		try {
         tx = session.beginTransaction();
			obj = session.load(clazz, id);
			tx.commit();
		} catch (HibernateException e) {
			handleException(e);
		}
		return obj;
	}

	protected Object find(Class clazz, Integer id) throws DataAccessLayerException {
		Object obj = null;
		try {
         tx = session.beginTransaction();
			obj = session.load(clazz, id);
			tx.commit();
		} catch (HibernateException e) {
			handleException(e);
		}
		return obj;
	}

	protected List findAll(Class clazz) throws DataAccessLayerException {
		List objects = null;
		try {
         tx = session.beginTransaction();
			Query query = session.createQuery(" FROM " + clazz.getName());
			objects = query.list();
			tx.commit();
		} catch (HibernateException e) {
			handleException(e);
		}
		return objects;
	}

	protected Session getSession() {
		return session;
	}

	protected Transaction getTx() {
		return tx;
	}

	protected void startOperation() throws HibernateException, DataAccessLayerException {
		session = HibernateUtil.openSession();
	}

	protected void handleException(HibernateException e) throws DataAccessLayerException {
		if (tx != null) {
			tx.rollback();
		}
		throw new DataAccessLayerException(e);
	}

	protected void handleExceptionNoTransaction(HibernateException e) {
		throw new DataAccessLayerException(e);
	}
}
